package com.fitns.user.advice;

import com.fitns.user.conf.ZhhwResp;
import com.fitns.user.exception.BaseException;
import com.fitns.user.exception.CommMsgCode;
import com.fitns.user.exception.MsgCode;
import com.fitns.user.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.sql.SQLException;

import static com.fitns.user.exception.CommMsgCode.OTHER_ERROR;
import static com.fitns.user.exception.CommMsgCode.PARAM_ERROR;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * 全局异常处理
 */

@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {

	@Autowired
	private RedisUtil redisUtil;

	/*@Resource
	private EmailHandler emailHandler;*/

	@ExceptionHandler(value = Exception.class)
	public ZhhwResp<?> onException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.error("uri:[" + request.getRequestURI() + "]," + e.getMessage(), e);


		if (e instanceof SQLException || e instanceof DataAccessException) {
			return createErrorResp(CommMsgCode.DB_ERROR, null, request, response);
		} /*else if (e instanceof FatalException) {
			FatalException ex = (FatalException) e;
			// 异步发送邮件
			emailHandler.asyncMail(SYSTEM_ERROR.getMessage(), ExceptionUtils.getStackTrace(ex));
			return createErrorResp(ex.getMsgCode(), ex.getMessage(), request, response);
		}*/ else if (e instanceof BaseException) {
			BaseException ex = (BaseException) e;
		//	processToPageWeixin(ex,request,response);
			return createErrorResp(ex.getMsgCode(), ex.getMessage(), request, response);
		} else if (e instanceof MissingServletRequestParameterException
				|| e instanceof BindException
				|| e instanceof ConstraintViolationException
				|| e instanceof TypeMismatchException
				|| e instanceof ServletRequestBindingException) {
			return createErrorResp(PARAM_ERROR, "请求参数错误", request, response);
		} else {
			return createErrorResp(OTHER_ERROR, "服务器错误", request, response);
		}
	}


//	private void processToPageWeixin(BaseException ex, HttpServletRequest request, HttpServletResponse response) throws IOException {
//		String uri = request.getRequestURI();
//		if(CommMsgCode.UNAUTHORIZED.equals(ex.getMsgCode()) && uri.endsWith("api/toPage/wx")) {
//			try {
//				String token = ContextUtils.getToken();
//				String toPageName = request.getParameter("pageName");
//				redisUtil.setex(RedisKey.REDIRECT_URL.of(token), toPageName);
////				request.getRequestDispatcher("/api/openid/wx/for?pageName="+toPageName).forward(request, response);
//				//重定向到nginx微信页面
//				response.sendRedirect("/tms/api/openid/wx/for?pageName="+toPageName);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}


	private ZhhwResp<?> createErrorResp(MsgCode msgCode, String message, HttpServletRequest request, HttpServletResponse response) throws IOException {
		ZhhwResp<String> zhhwResp = new ZhhwResp<>();
		zhhwResp.setCode(msgCode.getCode());
		zhhwResp.setMessage(isNotBlank(message) ? message : msgCode.getMessage());
		if(msgCode instanceof Enum) {
			Enum<?> e = (Enum<?>) msgCode;
			zhhwResp.setResultCode(e.name());
		}
		return zhhwResp;
	}

}
